package ua.races.command.implementation;

import ua.races.dao.RacesDaoImpl;
import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import ua.races.vo.Bet;
import ua.races.vo.Client;
import ua.races.vo.Race;
import ua.races.vo.Bet;
import ua.races.vo.Client;
import ua.races.vo.Race;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;


public class ViewOldBetsCommand implements ServletCommand {

    private static final Logger log = Logger.getLogger(ViewOldBetsCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        final String email = req.getParameter("email");
        final long password = req.getParameter("password").hashCode();
        final Client client;
        final HttpSession session;
        log.info("create parameters for view old client's bets");

        try {
            RacesDaoImpl dao = (RacesDaoImpl) context.getAttribute("DAO");
            client = dao.findClientByEmail(email);

            if ((client != null) && (client.getPassword() == password)) {
                // todo isRequestedSessionIdValid - ?
                // if ((true) || (!req.isRequestedSessionIdValid())) {
                session = req.getSession(true);
                session.setAttribute("client", client);
                List<Bet> bets = dao.findAllClientBets(client);
                session.setAttribute("bets",bets);
                // todo List<Race> races = dao.findAllRacesForBet();
                List<Race> races = dao.findAllRaces();
                session.setAttribute("races",races);
                // }
                log.info("Client : " + client.getLastName() + " " + client.getFirstName() +
                        " just has come to his account");
                context.getRequestDispatcher("/client.jsp").forward(req, resp);
            } else {
                req.setAttribute("passIsCorrect", false);
                log.info("Attempt to login with incorrect data");
                context.getRequestDispatcher("/index.jsp").forward(req, resp);
            }

        } catch (SQLException e) {
            log.error(e);
        } catch (ServletException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }


    }
}
